package com.example.springtest.exam.service.impl;


import com.example.springtest.common.ServiceCode;
import com.example.springtest.common.ServiceException;
import com.example.springtest.course.mapper.CourseMapper;
import com.example.springtest.course.pojo.entity.Course;
import com.example.springtest.exam.mapper.ExamMapper;
import com.example.springtest.exam.pojo.Exam;
import com.example.springtest.exam.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ExamServiceImpl implements ExamService {
    @Autowired
    private ExamMapper examMapper;
@Autowired
private CourseMapper courseMapper;

    @Override
    public List<Exam> getExamList(){
        List<Exam> examList=examMapper.getList();
        if(examList==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在考试！");
        }
        return examList;
    }

    @Override
    public void addExam(Exam exam){
        Course course =courseMapper.getByName(exam.getName());
        if(course==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在该课程!");
        }
        int result = examMapper.add(exam);
        if(result!=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"添加失败！");
        }
    }

    @Override
    public void deleteExam(Integer id){
        int result = examMapper.delete(id);
        if(result!=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"删除失败！");
        }
    }
    @Override
    public void editExam(Integer id,Exam exam){
        Course course =courseMapper.getByName(exam.getName());
        if(course==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在该课程!");
        }
        Exam exam1=examMapper.getById(id);
        exam1.setName(exam.getName());
        exam1.setAddress(exam.getAddress());
        exam1.setDate(exam.getDate());
        exam1.setStart_time(exam.getStart_time());
        exam1.setEnd_time(exam.getEnd_time());
        int result = examMapper.edit(exam1);
        if(result!=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"删除失败！");
        }

    }

    @Override
    public Exam updateStatus(Integer id){
    Exam exam=examMapper.getById(id);
    if(exam==null){
        throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在考试！");
    }
    exam.setStatus("已完成");
        int result = examMapper.updateStatus(exam);
        if (result <= 0) {
            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "更新失败！");
        }
        return exam;
    }
    }

